var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require("compression");
var session = require("express-session");
var RedisStore = require("connect-redis")(session);
var cf = require("./utils/config");
var log4j = require("./utils/log4j");


var see = require("./routes/see/indexApp");
var enjoy = require("./routes/enjoy/indexApp");
var happyi = require("./routes/happyi/indexApp");
var purchase = require("./routes/purchase/indexApp");
var friend = require("./routes/friend/indexApp");

global.loginfo = log4j.infoLog;
global.logerror = log4j.errorLog;

var app = express();
app.use(compression());
app.locals.$version = require("./package.json").version;
app.disable('x-powered-by');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.maxSockets=cf.maxSockets;
app.set('env', cf.env);
app.use(logger(':remote-addr :method :url  :status  :response-time ms :user-agent', {
  stream: {
    write: function(str){
      var srr = str.split("  ");
      if(srr[1] === "200" || srr[1] == "304")
        global.loginfo(str);
      else global.logerror(str);
    }
  },
  immediate:false
}));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser(cf.cookieSecret));
// app.use(favicon(path.join(__dirname, 'public', 'imgs', 'favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));




app.use(session({
  store:new RedisStore(cf.redisSessionOption),
  secret: cf.redisSessionOption.secret,
  resave:true,
  secure:false,
  saveUninitialized:false,
  cookie:{maxAge:cf.redisSessionOption.maxAge}
}));


//乐看
app.use("/",see);
//乐友
app.use("/friend",friend);
//乐i
app.use("/happyi",happyi);
//乐购
app.use("/purchase",purchase);
//乐娱
app.use("/enjoy",enjoy);

app.all("*", function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error',{title:"出错了",message:err.stack});
});

module.exports = app;
